package edu.colorado.karl.mainsched;

import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * SchedulerThread is a Thread that controls invocation of the Intelligent Scheduler.
 * @see edu.colorado.karl.intelsched.SetPointEvaluator
 */
public class SchedulerThread extends Thread {
	//	Used for log4j logging
	private static final Log log = LogFactory.getLog(SchedulerThread.class);

	/**
	 * Sole constructor.
	 */
	public SchedulerThread() {
	}
	
	/**
	 * Runs the SchedulerThread.  The thread will wake up every hour to invoke
	 * the Intelligent Scheduler, and then return to sleep.
	 */
	public void run() {
		Calendar cal = Calendar.getInstance();
		int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
		boolean run = false;
		ModeSwitch ms = new ModeSwitch();
		
		while(true) {
			//	Check if it is time to run
			cal = Calendar.getInstance(); // Update the clock
			
			if(hourOfDay != cal.get(Calendar.HOUR_OF_DAY)) {
				if(run == true)
					log.warn("SchedulerThread: Something wrong with the scheduler, skipped an update.");
				
				run = true;
				hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
			}
			
			if(run) {
				run = false;
				//	Start processing

				log.debug("SchedulerThread: Invoking the Intelligent Scheduler.");
				//	Call Mode Switch, tell it to run the IS
				ms.run();
			}
			
			//	Now, sleep
			try {
				Thread.sleep(60000);	// check time every minute
			} catch (InterruptedException e) {
				break;
			}
		}
	}
}
